<template>
  <div>
    <el-form :model="form" label-width="auto">
      <el-form-item label="名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="图标">
         <el-upload
          class="avatar-uploader"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><UserFilled /></el-icon>
          <div class="avatar-uploader-tip">更换图标</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="上级组">
        <el-tree-select
          v-model="form.parent_id"
          :data="tableData"
          check-strictly
          filterable
          :render-after-expand="false"
          node-key="id"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
      <el-form-item label="成员">
        <el-select v-model="form.user_group_members" multiple filterable placeholder="请选择">
          <!-- 自定义tag -->
          <template #tag>
            <div class="user-group-members-tag" v-for="item in form.user_group_members" :key="item.id">
              <div class="user-group-members-tag-icon shrink-0"></div>
              <div class="user-group-members-tag-name">
                <div v-if="item.type === 'user'">{{ item.name }}({{ item.email }})</div>
                <div v-if="item.type === 'group'">
                  {{ item.name }}<span class="user-group-members-tag-name-group">群组</span>
                </div>
              </div>
              <el-icon class="user-group-members-tag-close shrink-0"><CloseBold /></el-icon>
            </div>
          </template>
          <!-- 自定义搜索框 -->
          <template #default>
            <div class="user-group-members">
              <!-- 占位 -->
              <div class="user-group-members-hide">
                <el-option label="Action 1" value="1" />
              </div>
              <!-- 实际显示的 -->
              <div class="user-group-members-show">
                <div class="user-group-members-tip">可能找到的用户/组</div>
                <div class="flex">
                  <div class="flex-1 user-group-members-list">
                    <el-scrollbar height="200px">
                      <div
                        class="user-group-members-item"
                        :class="{ active: item.id === userGroupActive?.id }"
                        v-for="item in userAndUserGroupList"
                        :key="item.id"
                        @click="userGroupActive = item"
                      >
                        <div class="user-group-members-item-icon shrink-0"></div>
                        <div class="user-group-members-item-name">
                          <template v-if="item.type === 'user'">
                            {{ item.name }}({{ item.email }})
                          </template>
                          <div v-if="item.type === 'group'">
                            <div>{{ item.name }}</div>
                            <div>腾讯/光子工作室群/美术组</div>
                          </div>
                        </div>
                        <el-icon v-if="item.type === 'group'" class="user-group-members-item-caret shrink-0"><CaretRight /></el-icon>
                      </div>
                    </el-scrollbar>
                  </div>
                  <div class="user-group-members-option shrink-0" v-if="userGroupActive && userGroupActive.type === 'group'">
                    <div class="user-group-members-option-li">
                      <span class="user-group-members-option-li-title">添加全部用户</span>
                      <el-tooltip placement="top" effect="light">
                        <template #content>所选部门/用户组的全部成员将以个人<br/>用户身份添加入目标用户组中</template>
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                    <div class="user-group-members-option-li">
                      <span class="user-group-members-option-li-title">关联群组</span>
                      <el-tooltip placement="top" effect="light">
                        <template #content>所选部门/用户组将以群组身份添加入目标<br/>用户组中，且群组成员的增删改会实时同<br/>步目标用户组的权限</template>
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-select>
        <div class="flex justify-between items-center user-group-members-count">
          <div class="user-group-members-count-left">当前成员（{{ userCount }}），群组（{{ groupCount }}）</div>
          <div class="user-group-members-count-right">一键导入</div>
        </div>
      </el-form-item>
      <div class="flex justify-end">
        <el-button @click="onCloseDrawer">取消</el-button>
        <el-button type="primary" @click="onSubmit">配置权限</el-button>
      </div>
    </el-form>
  </div>

</template>
<script setup lang="ts">
import { onMounted, ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UserFilled,
  CloseBold,
  CaretRight,
  QuestionFilled,
} from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import http from '@/api/index'

const emits = defineEmits<{
  (e: 'onConfigPermissions', value: any): void
  (e: 'onCloseDrawer', value: boolean): void
}>()

const userCount = computed(() => 
  form.user_group_members.filter(item => item.type === 'user').length
)
const groupCount = computed(() => 
  form.user_group_members.filter(item => item.type === 'group').length
)

interface UserGroup {
  name: string,
  icon_url: string,
  parent_id: string,
  description: string,
  inherit_mode: number,
  user_group_members: any[]
}
const form = reactive<UserGroup>({
  name: '',
  icon_url: '',
  parent_id: '',
  description: '',
  inherit_mode: 0,
  user_group_members: [
    {
      member_id: 99120641686286,
      member_type: 'person',
      type: 'user',
      name: '张三',
      email: 'zhangsan@example.com',
    },
    {
      member_id: 99120641772662,
      member_type: 'person',
      type: 'user',
      name: '李四',
      email: 'lisi@example.com',
    }
  ],
})

const userGroupActive = ref()

const imageUrl = ref('')

// 配置权限
const onSubmit = async () => {
  emits('onConfigPermissions', form)
}

// 取消
const onCloseDrawer = () => {
  emits('onCloseDrawer', false)
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  _response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


// 用户和用户组
const userAndUserGroupList = ref<any[]>([
  // {
    //   name: 'Tom',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'user',
    //   id: 1,
    // },
    // {
    //   name: 'Tom255555',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'group',
    //   id: 2,
    // },
    // {
    //   name: 'Tom8562323',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'user',
    //   id: 3,
    // },
    // {
    //   name: 'Tom632325652322',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'group',
    //   id: 4,
    // },
    // {
    //   name: 'Tom962323232',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'user',
    //   id: 5,
    // },
    // {
    //   name: 'Tom29562323232',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'group',
    //   id: 6,
    // },
    // {
    //   name: 'Tom777889',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'user',
    //   id: 7,
    // },
    // {
    //   name: 'Tom23722',
    //   email: 'tom@example.com',
    //   icon: '',
    //   type: 'group',
    //   id: 8,
    // }
])
const getUserAndUserGroup = async () => {
  const res = await http.api.getUserAndUserGroup()
  if (res.result) {
    userAndUserGroupList.value = addLabelValue(res.result.data)
  }
}


// 获取用户组列表
const tableData = ref<any[]>([])
const addLabelValue = (tree: any[]) => {
  return tree.map(item => {
    const newItem = {
      ...item,
      label: item.name,
      value: item.id,
    }
    if (item.children && item.children.length > 0) {
      newItem.children = addLabelValue(item.children)
    }
    return newItem
  })
}
const getUserGroup = async () => {
  const res = await http.api.getUserGroup()
  if (res.result) {
    tableData.value = addLabelValue(res.result.data)
  }
}

onMounted(() => {
  getUserGroup()
  if (false) {
    getUserAndUserGroup() // 获取用户和用户组
  }
})

</script>

<style lang="scss" scoped>
// 人员选择
.user-group-members-tag {
  display: flex;
  align-items: center;
  padding: 4px 6px;
  padding-right: 10px;
  border: 1px solid var(--el-border-color);
  border-radius: 20px;
  .user-group-members-tag-icon {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    margin-right: 6px;
    background-color: #1890ff;
  }
  .user-group-members-tag-name {
    flex: 1;
    .user-group-members-tag-name-group{
      background-color: #00e56d;
      color: #000;
      padding: 0px 6px;
      border-radius: 4px;
      margin-left: 4px;
      font-size: 12px;
    }
  }
  .user-group-members-tag-close {
    margin-left: 6px;
    cursor: pointer;
    &:hover {
      color: #fff;
    }
  }
}
.user-group-members {
  width: 100%;
  overflow: hidden;
  position: relative;
  .user-group-members-hide {
    opacity: 0;
    position: absolute;
    right: -1000px;
    top: -1000px;
  }
  .user-group-members-show {
    .user-group-members-tip {
      padding: 0 15px 6px;
      color:#555;
    }
    .user-group-members-list {
      .user-group-members-item {
        padding: 0px 10px;
        height: 50px;
        display: flex;
        align-items: center;
        cursor: pointer;
        &:hover,
        &.active {
          background-color: #21354b;
        }
        .user-group-members-item-icon {
          width: 35px;
          height: 35px;
          border-radius: 50%;
          background-color: #1890ff;
          margin-right: 10px;
        }
        .user-group-members-item-name {
          flex: 1;
          color: #acb1bc;
        }
        .user-group-members-item-caret {
          margin-left: 6px;
        }
      }
    }
    .user-group-members-option {
      width: 150px;
      border-left: 1px solid #535353;
      .user-group-members-option-li {
        height: 30px;
        padding: 0 10px;
        display: flex;
        align-items: center;
        color: #acb1bc;
        cursor: pointer;
        &:hover {
          background-color: #21354b;
        }
        .user-group-members-option-li-title {
          padding-right: 10px;
        }
      }
    }
  }
}
.user-group-members-count {
  width: 100%;
  padding-top: 10px;
  .user-group-members-count-left {
    color: #838183;
  }
  .user-group-members-count-right {
    cursor: pointer;
    color: #1890ff;
  }
}

// 上传头像
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #fff;
  width: 100px;
  height: 100px;
  border-radius: 4px;
  text-align: center;
  background-color: #00e56d;
}
.avatar-uploader-tip {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100px;
  text-align: center;
  font-size: 12px;
  color: #fff;
  line-height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
}

// 抽屉标题
.drawer-title {
  background-color: #2b2b2b;
  padding: 10px 20px;
  margin-bottom: 20px;
}


</style>
